package com.wsoft.hr.pm.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.wsoft.hr.pm.entity.HrPmTargetEntity;
import com.wsoft.hr.pm.query.target.*;
import com.wsoft.hr.pm.service.IHrPmTargetService;
import com.wsoft.hr.pm.util.TargetCalculateScoreUtil;
import com.wsoft.hr.pm.vo.target.TargetVO;
import com.wsoft.response.ResponsePage;
import com.wsoft.response.ResponseResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 指标库 前端控制器
 * @author Z001
 * @since 2025年02月17日 15:06:35
 */
@RestController
@Tag(name = "指标")
@RequestMapping("/hr/pm/target")
public class HrPmTargetController {

    @Resource
    private IHrPmTargetService targetService;


    @Operation(summary = "新增指标-保存", description = "新增指标")
    @PostMapping("/insert")
    public ResponseResult insert(@RequestBody @Valid TargetInsertQuery query) {
        boolean b = targetService.insertTarget(query,false);
        if (b) {
            return ResponseResult.success("[sys.msg.success]");
        } else {
            return ResponseResult.failed("[sys.msg.failed]");
        }
    }

    @Operation(summary = "新增指标-保存并提交", description = "新增指标-保存并提交")
    @PostMapping("/insertSubmit")
    public ResponseResult insertSubmit(@RequestBody @Valid TargetInsertQuery query) {
        boolean b = targetService.insertTarget(query,true);
        if (b) {
            return ResponseResult.success("[sys.msg.success]");
        } else {
            return ResponseResult.failed("[sys.msg.failed]");
        }
    }


    @Operation(summary = "编辑指标", description = "编辑指标")
    @PostMapping("/update")
    public ResponseResult update(@RequestBody @Valid TargetUpdateQuery query) {
        boolean b = targetService.updateTarget(query,false);
        if (b) {
            return ResponseResult.success("[sys.msg.success]");
        } else {
            return ResponseResult.failed("[sys.msg.failed]");
        }
    }

    @Operation(summary = "编辑指标状态", description = "编辑指标状态")
    @PostMapping("/updateStatus")
    public ResponseResult updateStatus(@RequestBody @Valid TargetUpdateQuery query) {
        boolean b = targetService.updateStatus(query);
        if (b) {
            return ResponseResult.success("[sys.msg.success]");
        } else {
            return ResponseResult.failed("[sys.msg.failed]");
        }
    }


    @Operation(summary = "编辑指标-并提交", description = "编辑指标-并提交")
    @PostMapping("/updateSubmit")
    public ResponseResult updateSubmit(@RequestBody @Valid TargetUpdateQuery query) {
        boolean b = targetService.updateTarget(query,true);
        if (b) {
            return ResponseResult.success("[sys.msg.success]");
        } else {
            return ResponseResult.failed("[sys.msg.failed]");
        }
    }

    @Operation(summary = "指标详情", description = "指标详情")
    @GetMapping("/get")
    public ResponseResult get(@RequestParam("id") Long id) {
        return ResponseResult.success(targetService.getTargetInfo(id));
    }

    @Operation(summary = "删除指标", description = "删除指标")
    @GetMapping("/delete")
    public ResponseResult delete(@RequestParam("id") Long id) {
        boolean b = targetService.delete(id);
        if (b) {
            return ResponseResult.success("[sys.msg.success]");
        } else {
            return ResponseResult.failed("[sys.msg.failed]");
        }
    }

    @Operation(summary = "指标分页", description = "指标分页")
    @PostMapping("/list")
    public ResponseResult list(@RequestBody TargetListQuery query) {
        PageInfo page = targetService.listTarget(query,false);
        List<HrPmTargetEntity> list = page.getList();
        List<TargetVO> resultList = new ArrayList<>();
        for (HrPmTargetEntity targetEntity : list) {
            TargetVO targetVO = Convert.convert(TargetVO.class, targetEntity);
            targetVO.setUpdateWeight(false);
            targetVO.setUpdateStandard(false);
            targetVO.setUpdateGroupId(false);
            targetVO.setUpdateParTargetId(false);
            targetVO.setUpdateRemark(false);
            if (null == targetVO.getWeight() || targetVO.getWeight().compareTo(BigDecimal.ZERO) == 0) {
                targetVO.setUpdateWeight(true);
            }
            if(StrUtil.isBlank(targetVO.getStandard())){
                targetVO.setUpdateStandard(true);
            }
            if(null == targetVO.getGroupId() || targetVO.getGroupId() == 0){
                targetVO.setUpdateGroupId(true);
            }
            if(null == targetVO.getUpdateParTargetId()){
                targetVO.setUpdateParTargetId(true);
            }
            if(StrUtil.isBlank(targetVO.getRemark())){
                targetVO.setUpdateRemark(true);
            }
            resultList.add(targetVO);
        }
        page.setList(resultList);
        return ResponseResult.success(ResponsePage.restPage(page));
    }

    @Operation(summary = "指标分页-下拉查询", description = "指标分页-下拉查询")
    @PostMapping("/listEnable")
    public ResponseResult listEnable(@RequestBody TargetListQuery query) {
        query.setEnableFlag(1);
        PageInfo<HrPmTargetEntity> page = targetService.listTarget(query,false);
        return ResponseResult.success(ResponsePage.restPage(page));
    }

    @Operation(summary = "模板导出", description = "模板导出")
    @PostMapping("/templateExport")
    public void templateExport(HttpServletResponse response) {
        ByteArrayOutputStream outputStream = targetService.templateExport();

        byte[] excelBytes = outputStream.toByteArray();

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=output.xlsx");

        // 将字节数组写入响应输出流
        try (OutputStream out = response.getOutputStream()) {
            out.write(excelBytes);
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Operation(summary = "指标导出", description = "指标导出")
    @PostMapping("/export")
    public void export(HttpServletResponse response , @RequestBody TargetExportQuery query) {
        ByteArrayOutputStream outputStream = targetService.exportTarget(query);

        byte[] excelBytes = outputStream.toByteArray();

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=output.xlsx");

        // 将字节数组写入响应输出流
        try (OutputStream out = response.getOutputStream()) {
            out.write(excelBytes);
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @Operation(summary = "指标导入", description = "指标导入")
    @PostMapping("/import")
    public ResponseResult importExcel(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        targetService.importExcel(multipartFile.getInputStream());
        return ResponseResult.success("[sys.msg.success]");
    }


    @Operation(summary = "公式计算分数", description = "公式计算分数")
    @PostMapping("/calculateScore")
    public ResponseResult calculateScore(@RequestBody CalculateScoreQuery query){
        return ResponseResult.success(TargetCalculateScoreUtil.calculateScore(query));
    }


}
